<template>
    <div class="collect-box">
        <el-form :model="baseData" :rules="rules" ref="collectData" :inline="false" label-width="120px" class="act-rule-form">
            <el-form-item label="征集活动名称" prop="title" required>
                <el-input v-model="baseData.title" type="input" style="min-width:400px"></el-input>
            </el-form-item>
            <el-form-item label="活动期数" prop="phase" required>
                <el-input v-model="baseData.phase" type="number" style="width:150px"></el-input>
            </el-form-item>
            <el-form-item label="副标题" prop="subTitle" required>
                <el-input v-model="baseData.subTitle" autosize type="textarea" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="投稿限制" prop="timeType" required>
                <el-select style="width:150px;" v-model="baseData.timeType">
                    <el-option label="不限" :value="0"></el-option>
                    <el-option label="单人仅一次" :value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="活动时间" prop="startTime" required>
                <el-date-picker
                    v-model="validBeginDate"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="dateChange">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="限定勋章" prop="rewardMedalType" required>
                    <el-select @change="medalChange" style="width:150px;" v-model="baseData.rewardMedalType">
                        <el-option :label="item.name" :value="item.medalType" v-for="(item, index) in medalList" :key="index"></el-option>
                    </el-select>
                </el-form-item>
            <el-form-item label="H5链接" prop="webUrl">
                <el-input v-model="baseData.webUrl" type="input" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status" required>
                <el-radio-group v-model="baseData.status">
                    <el-radio :label="1">上架</el-radio>
                    <el-radio :label="0">下架</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="征集活动介绍" prop="desc" required>
                <el-input v-model="baseData.desc" autosize type="textarea" style="width:400px;"></el-input>
            </el-form-item>
            <div>
                <el-form-item label="征集活动海报" required>
                    <UploadImg v-model="baseData.cover" :boxWidth="boxWidth" :boxHeight="boxHeight" :width="imgWidth" :height="imgHeight" :search="false" />
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import { formatDate } from '@/utils/utils'
import E from 'wangeditor'
export default {
    props: {
        collectionActivityVo: {},
        baseChange: {
            type: Function,
            default: null
        }
    },
    data () {
        return {
            baseData: this.collectionActivityVo,
            validBeginDate: [],
            medalList: [],
            imgWidth: parseInt(this.$route.query.targetType) === 1 ? '537' : '672',
            imgHeight: parseInt(this.$route.query.targetType) === 1 ? '900' : '672',
            boxWidth: parseInt(this.$route.query.targetType) === 1 ? '179' : '168',
            boxHeight: parseInt(this.$route.query.targetType) === 1 ? '300' : '168',
            pickerOptions: {
                disabledDate (time) {
                    return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
                },
                selectableRange: '00:00:00 - 23:59:59'
            },
            rules: {
                title: [
                    { required: true, message: '请填写征集活动名称', trigger: ['blur', 'change'] }
                ],
                subTitle: [
                    { required: true, message: '请填写副标题', trigger: ['blur', 'change'] }
                ],
                phase: [
                    { required: true, message: '请填写期数', trigger: ['blur', 'change'] }
                ],
                timeType: [
                    { required: true, message: '请选择投稿限制', trigger: ['blur', 'change'] }
                ],
                startTime: [
                    { required: true, message: '请选择活动时间', trigger: ['blur', 'change'] }
                ],
                status: [
                    { required: true, message: '请选择活动状态', trigger: ['blur', 'change'] }
                ],
                desc: [
                    { required: true, message: '请填写活动介绍', trigger: ['blur', 'change'] }
                ],
                rewardMedalType: [
                    { required: true, message: '请选择勋章', trigger: 'change' }
                ]
            }
        }
    },
    created () {
        this.targetType = parseInt(this.$route.query.targetType)
        this.pickerOptions.selectableRange = formatDate((+new Date() + 10 * 60 * 1000), 'HH:MM:SS') + ' - 23:59:59'
        this.activityId = this.$route.query.id || null
        if (!this.activityId) this.baseData.startTime = ''
        this.getMedal()
    },
    mounted () {
        if (this.activityId) {
            this.validBeginDate = [new Date(this.baseData.startTime), new Date(this.baseData.endTime)]
        }
        // this.createEditor()
    },
    watch: {
        'baseData': {
            handler: function (data) {
                this.baseChange(data)
            },
            immediate: true
        }
    },
    methods: {
        validateForm () {
            let flag = true
            this.$refs[`collectData`].validate(valid => {
                if (!valid) {
                    flag = false
                }
            })
            this.baseChange(this.baseData)
            return flag
        },
        getMedal () {
            let params = {
                pageNum: 1,
                pageSize: 999,
                type: 1
            }
            this.$http.get('/gameList/selectMedalConf', { params }).then(res => {
                if (res.code === '0') {
                    this.medalList = res.data
                } else {
                    this.$message({
                        type: 'error',
                        message: '系统异常，请稍后再试'
                    })
                }
            })
        },
        medalChange (val) {
            this.baseData.rewardMedalType = val
            this.medalList.map(item => {
                if (item.rewardMedalType === val) this.baseData.name = item.name
            })
        },
        dateChange (val) { // 活动时效时间修改
            if (!val) {
                this.baseData.startTime = ''
                this.baseData.endTime = ''
            } else {
                this.baseData.startTime = formatDate(val[0].getTime(), 'YYYY-MM-DD HH:MM:SS')
                this.baseData.endTime = formatDate(val[1].getTime(), 'YYYY-MM-DD HH:MM:SS')
            }
        },
        // 初始化富文本编辑器
        createEditor () {
            this.editor = new E(`#desc`)
            this.editor.customConfig.uploadImgServer = '/admin/file/uploadPic'
            this.editor.customConfig.uploadImgParams = {
                needTransform: 1
            }
            this.editor.customConfig.uploadFileName = 'file'
            this.editor.customConfig.uploadImgHooks = {
                before: function (xhr, editor, files) {
                // 图片上传之前触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件
                // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
                // return {
                //     prevent: true,
                //     msg: '放弃上传'
                // }
                },
                success: function (xhr, editor, result) {
                // 图片上传并返回结果，图片插入成功之后触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                fail: function (xhr, editor, result) {
                // 图片上传并返回结果，但图片插入错误时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                },
                error: function (xhr, editor) {
                // 图片上传出错时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },
                timeout: function (xhr, editor) {
                // 图片上传超时时触发
                // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
                },

                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
                customInsert: function (insertImg, result, editor) {
                // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
                // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

                    // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
                    var url = result.data
                    insertImg(url)

                // result 必须是一个 JSON 格式字符串！！！否则报错
                }
            }
            this.editor.customConfig.zIndex = 100
            this.editor.customConfig.menus = [
                // 'head', // 标题
                'bold', // 粗体
                // 'fontSize', // 字号
                // 'fontName', // 字体
                'italic', // 斜体
                'underline', // 下划线
                'strikeThrough', // 删除线
                'foreColor', // 文字颜色
                'backColor', // 背景颜色
                'link', // 插入链接
                // 'list', // 列表
                'justify', // 对齐方式
                // 'quote', // 引用
                // 'emoticon', // 表情
                'image', // 插入图片
                // 'table', // 表格
                // 'video', // 插入视频
                // 'code', // 插入代码
                'undo', // 撤销
                'redo' // 重复
            ]
            this.editor.customConfig.onchange = (html) => {
                this.baseData.desc = html
            }
            this.editor.create()
            this.editor.txt.html(this.baseData.desc)
        }
    }
}
</script>

<style lang="scss" scoped>
    .collect-box {
        min-width: 800px;
        .act-rule-form {
            /deep/.el-form-item__content {
                margin-left: 0 !important;
            }
        }
        .btn-wrap {
            margin-left: 120px;
            margin-bottom: 20px;
        }
    }
</style>
